package com.crane.common.core.utils;


import java.util.HashMap;
import java.util.Map;


/**
 * @author zhenxing.pi
 */
public class BaseContextHandler {

    public static final String USER_ID="userId";

    public static final String RANDOM_KEY="randomKey";


    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void setUserId(String userId) {
        set(BaseContextHandler.USER_ID, userId);
    }

    public static Long getUserId() {
        return  getLong(BaseContextHandler.get(BaseContextHandler.USER_ID));
    }

    public static void setRandomKey(String randomKey) {
        set(BaseContextHandler.RANDOM_KEY, randomKey);
    }

    public static String getRandomKey() {
        return getString(BaseContextHandler.get(BaseContextHandler.RANDOM_KEY));
    }

    private static String getString(Object value) {
        return value == null ? null : value.toString();
    }

    private static Long getLong(Object value) {
        return value == null ? null : Long.valueOf(value.toString());
    }

    public static void remove() {
        threadLocal.remove();
    }
}
